from pydantic import BaseModel
from account.epark_account_service import EParkAccountService

from manager.task_manager import TaskManager
from manager.spider_manager import SpiderManager
from manager.proxy_manager import ProxyManager
from manager.account_manager import AccountManager

from model.error import ParkSpiderError, ParkSpiderErrorCode
from model.dbmodel import DbTask

from account.account_service import AccountService
from account.yima_account_service import YimaAccountService
from account.ymiot_account_service import YmiotAccountService
from account.yun_account_service import YunAccountService
from account.jie_account_service import JieAccountService
from account.su_account_service import SuAccountService
from account.ydt_account_service import YdtAccountService
from account.airun_account_service import AirunAccountService

from database.task_table import TaskTable
import spider_config as con

from typing import List

task_manager = TaskManager()

class TaskRequest(BaseModel):
    task_id: int
    options: int

def build_proxy_manager(proxy_url: str):
    proxy_manager = ProxyManager()
    proxy_manager.add_service(proxy_url)
    return proxy_manager


def build_account_manager(task_id = None):
    account_manager = AccountManager()

    su_account_service = SuAccountService()
    account_manager.add_service(con.su_park_id, su_account_service)

    yima_account_service = YimaAccountService(60 * 30)
    account_manager.add_service(con.yima_park_id, yima_account_service)

    ymiot_account_service = YmiotAccountService(60 * 3)
    account_manager.add_service(con.ymiot_park_id, ymiot_account_service)

    yun_account_service = YunAccountService(60 * 3)
    account_manager.add_service(con.yun_park_id, yun_account_service)

    jie_account_service = JieAccountService()
    account_manager.add_service(con.jie_park_id, jie_account_service)

    ydt_account_service = YdtAccountService()
    account_manager.add_service(con.ydt_park_id, ydt_account_service)

    epark_account_service = EParkAccountService()
    account_manager.add_service(con.epark_park_id, epark_account_service)

    airun_account_service = AirunAccountService(60 * 5)
    account_manager.add_service(con.airun_park_id, airun_account_service)
    
    for account_service in account_manager.all_service():
        account_service.set_task_id(task_id)

    return account_manager


def task(data: TaskRequest):
    task = None
    with TaskTable() as db:
        task = db.query(data.task_id)
        if not task:
            raise ParkSpiderError(ParkSpiderErrorCode.NotFoundTask, data.task_id)

    if data.options == 1:
        account_manager = build_account_manager(task.id)
        proxy_manager = build_proxy_manager(task.proxy)
        task_manager.start_task(task, account_manager, proxy_manager)
    elif data.options == 2:
        task_manager.stop_task(task)
    else:
        raise ParkSpiderError(ParkSpiderErrorCode.Unknow, data.options)